// common/request.js
import {BASE_URL, BASE_API, BEARER, HEADER_TOKEN} from "@/utils/constant.js";
import { global }  from "@/utils/index"

console.log('global', global.getToken())

interface optionsProps{
	url: string
	method: 'GET' | 'POST' | 'PUT' | 'DELETE',
	header?: {},
	data?: {
		[key: string]: any
	},
}
export function request(options: optionsProps) : Promise<any> {
  return new Promise((resolve, reject) => {
    // 初始化uni.request的默认配置
    const defaultConfig = {
      url: options.url,
      method: options.method || 'GET',
      header: {
        'content-type': 'application/json', // 默认值，可根据需要修改
        // 其他默认header
      },
      data: options.data || {},
      dataType: 'json',
    };

    // 合并用户传递的配置和默认配置
    const finalOptions = Object.assign({}, defaultConfig, {...options, url: BASE_URL + BASE_API + options.url});
	if(global.getToken()){
		finalOptions.header[HEADER_TOKEN] = `${BEARER}${global.getToken()}`
		// finalOptions.data[HEADER_TOKEN]= global.getToken()
	}
 
	// console.log('finalOptions', finalOptions);
	
	
    // 发起请求
    uni.request({
      ...finalOptions,
      success: (res:any) => {
		  const { data } = res;
        if (data?.status === '200') {
          resolve(res.data);
        } else {
			resolve(res.data)
          console.error(new Error(`Request failed with status code ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}